<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/8/2
 * Time: 15:27
 */

namespace app\command\company;

use app\admin\model\Company;
use app\company\model\Supplier;
use app\company\model\WarehouseStorageGoodsLogs;
use app\mini\model\StoreUserCredit;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use app\supplier\model\StatSupplier as StatSupplierModel;

class StatSupplier extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('supplier:stat')->setDescription('日统计')
             ->addArgument('date', Option::VALUE_REQUIRED, '日期', '')
             ->addArgument('type', Option::VALUE_REQUIRED, '类型', 1);//1.正常执行 2.执行昨天的(校准数据)
    }


    protected function execute(Input $input, Output $output)
    {
        $date = $input->getArgument('date');
        $type = $input->getArgument('type');
        if (!$date) $date = date('Ymd');//如果没有传入日期，则取当前日期
        if ($type == 2) $date = date('Ymd', strtotime('-1 day'));//如果是校准数据，则取前一天的日期
        $date = date('Y-m-d', strtotime($date));
        $output->writeln("开始执行日统计:{$date}");
        $model = new Company();
        $model->startTrans();
        try {
            Supplier::select()->each(function ($item) use ($date,$output) {
                $supplier_id = $item->id;
                $type       = 1;
                $year       = date('Y', strtotime($date));//年
                $month      = date('m', strtotime($date));//月
                $quarter    = ceil((date('m', strtotime($date))) / 3);//季度
                //销售金额
                $sales_amount = $item->warehouseStorageGoodsLogss()->type(2)->whereDay('create_time', $date)->sum('amount');
                //销售数量
                $sales_quantity = $item->warehouseStorageGoodsLogss()->type(2)->whereDay('create_time', $date)->sum('quantity');
                //订单数量
                $order_quantity = $item->warehouseStorageGoodsLogss()->type(2)->group('store_order_id')->whereDay('create_time', $date)->count();
                //退货数量
                $return_quantity = 0;
                //退货金额
                $return_amount = 0;
                //回款金额 todo 订单账期到期时间
                $store_order_ids   = StoreUserCredit::whereDay('credit_time', $date)->column('store_order_id');
                $collection_amount = WarehouseStorageGoodsLogs::supplierId($item->id)->type(2)->whereIn('store_order_id', $store_order_ids)->sum('amount');
                //实收金额 支付方式不等于账期支付的金额
                $received_amount = (new WarehouseStorageGoodsLogs())->alias('ware')
                                                                    ->join(['dt_store_order' => 'order'], 'order.id=ware.store_order_id')
                                                                    ->where('ware.type', 2)
                                                                    ->whereDay('ware.create_time', $date)
                                                                    ->where('ware.supplier_id', $item->id)
                                                                    ->where('order.pay_type', '<>', 3)
                                                                    ->sum('ware.amount');
                //账期金额
                $bill_amount = (new WarehouseStorageGoodsLogs())->alias('ware')
                                                                ->join(['dt_store_order' => 'order'], 'order.id=ware.store_order_id')
                                                                ->where('ware.type', 2)
                                                                ->whereDay('ware.create_time', $date)
                                                                ->where('ware.supplier_id', $item->id)
                                                                ->where('order.pay_type', 3)
                                                                ->sum('ware.amount');
                //采购金额 统计已完成状态的

                $purchase_amount = $item->warehouseStorageGoodsLogss()->type(1)->whereDay('create_time', $date)->sum('amount');;
                //采购数量
                $purchase_quantity = $item->warehouseStorageGoodsLogss()->type(1)->whereDay('create_time', $date)->sum('quantity');
                //采购订单数量
                $purchase_order_quantity = $item->warehouseStorageGoodsLogss()->type(2)->group('company_order_id')->whereDay('create_time', $date)->count();

                $arr = compact('sales_amount', 'sales_quantity', 'order_quantity', 'return_quantity', 'return_amount', 'collection_amount',
                    'received_amount', 'bill_amount', 'purchase_amount', 'purchase_quantity', 'purchase_order_quantity', 'supplier_id', 'type',
                    'year', 'month', 'quarter');
                if (!$model = StatSupplierModel::supplierId($item->id)->whereDay('create_time', $date)->type(1)->find()) {
                    $model = new StatSupplierModel();
                }
                $model->save($arr);

                $field = "sum(sales_amount) sales_amount, sum(sales_quantity) sales_quantity,sum(order_quantity) order_quantity, sum(return_quantity) return_quantity,
              sum(return_amount) return_amount, sum(collection_amount) collection_amount, sum(received_amount) received_amount, sum(bill_amount) bill_amount, 
              sum(purchase_amount) purchase_amount, sum(purchase_quantity) purchase_quantity,  sum(purchase_order_quantity) purchase_order_quantity,min(supplier_id) supplier_id";

                //更新本年的
                if (!$yearModel = StatSupplierModel::supplierId($item->id)->type(5)->where('year', $year)->find()) {
                    $yearModel = new StatSupplierModel();
                }
                $arr         = StatSupplierModel::supplierId($item->id)->type(1)->where('year', $year)->field($field)->find()->toArray();
                $arr['year'] = $year;
                $arr['type'] = 5;
                $yearModel->save($arr);
                //更新季度的
                if (!$quarterModel = StatSupplierModel::supplierId($item->id)->type(4)->where('year', $year)->where('quarter', $quarter)->find()) {
                    $quarterModel = new StatSupplierModel();
                }
                $arr            = StatSupplierModel::supplierId($item->id)->type(1)->where('year', $year)->where('quarter', $quarter)->field($field)->find()->toArray();
                $arr['year']    = $year;
                $arr['quarter'] = $quarter;
                $arr['type']    = 4;
                $quarterModel->save($arr);
                //更新本月的
                if (!$monthModel = StatSupplierModel::supplierId($item->id)->type(3)->where('year', $year)->where('month', $month)->find()) {
                    $monthModel = new StatSupplierModel();
                }
                $arr          = StatSupplierModel::supplierId($item->id)->type(1)->where('year', $year)->where('month', $month)->field($field)->find()->toArray();
                $arr['year']  = $year;
                $arr['month'] = $month;
                $arr['type']  = 3;
                $monthModel->save($arr);
            });
            $model->commit();
            $output->writeln("执行成功");
        } catch (Exception $e) {
            $model->rollback();
            $output->writeln("执行失败----" . $e->getMessage(). "----" . $e->getLine(). "----" . $e->getFile());
        }
    }
}